package tt.love.hw.action;


import java.util.Date;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;



import tt.love.hw.COLASConstant;
import tt.love.hw.PMF;
import tt.love.hw.common.ActionContext;
import tt.love.hw.common.ViewRender;
import tt.love.hw.jdo.User;
import tt.love.hw.UserSessionInfo;


public class LoginAction {

	public ViewRender login(ActionContext actionContext) {
		User user = (User)actionContext.get("user");
		String userId = user.getUserId();
		String password = user.getPassword();
		String nextPage = "/login.jsp";
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			User loginuser = null;
			try {
				loginuser = pm.getObjectById(User.class, userId);
			} catch (JDOObjectNotFoundException e) {
				actionContext.put(COLASConstant.ERROR_MESSAGE, "error.user.notexist");
			}
			if (loginuser != null) {
				if (!password.equals(loginuser.getPassword())) {
					actionContext.put(COLASConstant.ERROR_MESSAGE, "error.incorrect.password");
				} else {
					nextPage = "/process/index.jsp";
					loginuser.setLastLoginDate(new Date());
					UserSessionInfo usersession = new UserSessionInfo();
					usersession.setUserid(loginuser.getUserId());
					usersession.setUsername(loginuser.getUserName());
					usersession.setRole(loginuser.getRole());
					usersession.setMateuserid(loginuser.getMateUserId());
					actionContext.getRequest().getSession().setAttribute("USI",usersession);
					
				}
			}
			return new ViewRender(nextPage);
		} finally {
			pm.close();
		}

	}
}
